package phone.example.com.a36kr.activity;

import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.litesuits.orm.LiteOrm;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import phone.example.com.a36kr.R;
import phone.example.com.a36kr.bean.LocalBean;
import phone.example.com.a36kr.bean.NewsSecondBean;
import phone.example.com.a36kr.bean.UserBean;
import phone.example.com.a36kr.nettool.NetTool;
import phone.example.com.a36kr.other.MyScrollview;
import phone.example.com.a36kr.other.SecondPopupWindow;
import phone.example.com.a36kr.other.mybmob.MyBmobUser;
import phone.example.com.a36kr.other.textimageurl.HtmlTextView;
import phone.example.com.a36kr.tools.BaseActivity;
import phone.example.com.a36kr.tools.DBTool;

/**
 * Created by dllo on 16/8/22.
 */
public class NewsSecondActivity extends BaseActivity implements MyScrollview.OnScrollListener {


    private HtmlTextView secondContentHtv;
    private String urlFormer = "https://rong.36kr.com/api/mobi/news/";
    private TextView secondTitleTv;
    private SecondPopupWindow menuWindows;
    private ImageView iconIm;
    private TextView writerTv;
    private TextView synopsisTv;// 简介
    private MyScrollview mScrollView;
    private LinearLayout below;
    private LinearLayout mLayout;
    private int searchLayoutBottom;
    private ImageView backIm;
    private String url;// 收藏的网址
    private String title; //简介
    private String iconUrl;//头像url
    private String writer; //要插入的作者
    private String bmobUrl;// 数据库查询的网址  用来对比是否收藏过
    private String columnName;//要插入的大公司
    private LiteOrm liteOrm;
    private ImageView collectIv;
    private ImageView moreIv;
    private PopupWindow mPopWindow; //更多pop

    private SeekBar seekBarLight;
    private int progress;

    @Override
    protected int setLayout() {
        return R.layout.activity_newssecond;
    }

    @Override
    protected void initView() {
        mLayout = bindView(R.id.activity_newssecond_linear_layout);
        secondContentHtv = bindView(R.id.news_second_contentHtv);
        secondTitleTv = bindView(R.id.news_second_title);
        iconIm = bindView(R.id.pop_second_head);
        writerTv = bindView(R.id.pop_second_writer);
        synopsisTv = bindView(R.id.pop_second_synopsis);
        mScrollView = bindView(R.id.news_second_scrollview);
        below = bindView(R.id.ll_below);
        //更多
        moreIv = bindView(R.id.news_second_more);
        moreIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow();
            }
        });

        ImageButton share = bindView(R.id.news_second_share);
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
            }
        });
        // 收藏按钮
        collectIv = bindView(R.id.news_second_collect);

        //***************************收藏**********************************//
        collectIv.setOnClickListener(new View.OnClickListener() {

            private UserBean userBean;

            @Override
            public void onClick(View v) {
                MyBmobUser user = MyBmobUser.getCurrentUser(MyBmobUser.class);
                if (user != null) {
                    final String userName = user.getUsername();//当前登录的用户名

                    DBTool.getInstance().unRepetition("contentUrl = ?", url, "name = ?", userName, new DBTool.QueryListener() {
                        @Override
                        public void onQueryComplete(ArrayList<LocalBean> localBeenn) {
                            if (localBeenn.size() != 0) {
                                liteOrm.delete(localBeenn);
                                collectIv.setImageResource(R.mipmap.mine_icon_favorite);
                                Toast.makeText(NewsSecondActivity.this, "取消收藏", Toast.LENGTH_SHORT).show();
                            } else {

                                final LocalBean localBean = new LocalBean();
                                localBean.setWriter(writer);
                                localBean.setTitle(title);
                                localBean.setContentUrl(url);
                                Log.d("当前登录的用户名", userName);
                                localBean.setName(userName);
                                localBean.setIcon(iconUrl);
                                localBean.setColumnName(columnName);//大公司
                                if (localBean != null) {
                                    DBTool.getInstance().insertData(localBean);
                                    collectIv.setImageResource(R.mipmap.news_toolbar_icon_favorite_blue);
                                    Toast.makeText(NewsSecondActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                                    Log.d("新闻详情界面", "数据插入成功");

                                } else {
                                    Toast.makeText(NewsSecondActivity.this, "收藏失败", Toast.LENGTH_SHORT).show();
                                    Log.d("NewsSecondActivity", "数据插入失败");
                                }

                            }
                        }
                    });

                    BmobQuery<UserBean> query = new BmobQuery<UserBean>();
                    userBean = new UserBean();
                    query.addWhereEqualTo("UserBean", url);
                    query.addWhereEqualTo("UserBean", user.getUsername());
                    query.setLimit(50);
                    query.findObjects(new FindListener<UserBean>() {
                        @Override
                        public void done(List<UserBean> list, BmobException e) {
                            if (e == null) {
                                if (list.size() == 0) {
                                    UserBean userBean = new UserBean();
                                    userBean.setUserName(userName);
                                    userBean.setWriter(writer);
                                    userBean.setTitle(title);
                                    userBean.setCollectUrl(url);
                                    userBean.setUserName(userName);
                                    userBean.setIcon(iconUrl);
                                    userBean.setColumnName(columnName);
                                    userBean.save(new SaveListener<String>() {
                                        @Override
                                        public void done(String s, BmobException e) {
                                            if (e == null) {
                                                Log.d("NewsSecondActivity", "数据创建成功");
                                            } else {
                                                Log.i("bm" +
                                                        "]", "失败：" + e.getMessage() + "," + e.getErrorCode());

                                            }
                                        }
                                    });
                                } else {
                                    userBean.setCollectUrl(url);
                                    userBean.delete(new UpdateListener() {
                                        @Override
                                        public void done(BmobException e) {
                                            if (e == null) {
                                                Log.d("NewsSecondActivity", "bmob 成功");
                                            } else {
                                                Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                                            }
                                        }
                                    });
                                }
                            } else {
                                Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                            }
                        }
                    });


                } else {
                    Toast.makeText(NewsSecondActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(NewsSecondActivity.this, RegisterActivity.class);
                    startActivity(intent);
                }
            }
            //*************************收藏***************************************//


        });

        backIm = bindView(R.id.news_second_back);
        backIm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // 第二页 点击显示下拉菜单按钮
        final LinearLayout ll = bindView(R.id.pop_window_ll);
        ll.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = getIntent();

                String cUrl = intent.getStringExtra("curl");
                String urlAdd = intent.getStringExtra("newsFeedId");
                if (cUrl != null) {
                    urlFormer = "";
                    urlAdd = "";
                } else {
                    cUrl = "";
                }
                url = cUrl + urlFormer + urlAdd;
                //实例化SecondPopupWindow
                menuWindows = new SecondPopupWindow(NewsSecondActivity.this, itemsOnClick);
                menuWindows.setUrlAdd(url);
                menuWindows.showAsDropDown(ll);//点击布局的ID
                menuWindows.showAtLocation(findViewById(R.id.pop_window_ll), Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 78);


            }
        });

    }

    @Override
    protected void initData() {
        liteOrm = LiteOrm.newSingleInstance(this, "MyDataBase.db");
        mScrollView.setOnScrollListener(this);

        /*****NewsFragment 传递过来的网址 postId*****/
        Intent intent = getIntent();

        String cUrl = intent.getStringExtra("curl");
        String urlAdd = intent.getStringExtra("newsFeedId");
        if (cUrl != null) {
            urlFormer = "";
            urlAdd = "";
            collectIv.setImageResource(R.mipmap.news_toolbar_icon_favorite_blue);

        } else {
            cUrl = "";
            collectIv.setImageResource(R.mipmap.mine_icon_favorite);
        }
        url = cUrl + urlFormer + urlAdd;
        Log.d("NewsSecondActivity", url);
        final NetTool mNetTool = new NetTool();
        mNetTool.getNetData(url, NewsSecondBean.class, new NetTool.NetListener<NewsSecondBean>() {


            @Override
            public void onSuccess(NewsSecondBean newsSecondBean) {
                // 解析并设置头像
                mNetTool.getImage(newsSecondBean.getData().getUser().getAvatar(), iconIm);
                iconUrl = newsSecondBean.getData().getUser().getAvatar();
                writerTv.setText(newsSecondBean.getData().getUser().getName());
                // 定义一个String 将作者存入
                writer = newsSecondBean.getData().getUser().getName();
                // 大公司
                columnName = newsSecondBean.getData().getColumnName();

                secondTitleTv.setText(newsSecondBean.getData().getTitle());
                // 收藏用的String title
                title = newsSecondBean.getData().getTitle();
                String html = newsSecondBean.getData().getContent();
                html.trim();
                html = html.replace("<p >", "<p>");
                html = html.replace("<blockquote >", "");
                html = html.replace("</blockquote>", "");
                html = html.replace("<br/>", "");
                html = html.replace("<ul  class=\" list-paddingleft-2\">", "");
                html = html.replace("</ul>", "");
                html = html.replace("</li>", "");
                html = html.replace("<li>", "");
//                Log.d("NewsChildActivity", html);
                secondContentHtv.setHtmlFromString(html, false);

            }

            @Override
            public void onError(String errorMsg) {
                Toast.makeText(NewsSecondActivity.this, "存储失败", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            menuWindows.dismiss();//SecondWindow 点击关闭

        }
    };

    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            searchLayoutBottom = mLayout.getBottom();//获取底部位置
        } else if (hasFocus == false) {


        }
    }


    @Override
    public void onScroll(int scrollY) {
        if (scrollY > searchLayoutBottom || scrollY < 0) {
            below.setVisibility(View.GONE);
        } else {
            below.setVisibility(View.VISIBLE);
        }
    }

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//        oks.setTitle(getString(R.string.share));
//         titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(this);
    }

    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(NewsSecondActivity.this).inflate(R.layout.news_second_popuplayout, null);

        mPopWindow = new PopupWindow(contentView,
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true);
        mPopWindow.setContentView(contentView);
        // seekBar
        seekBarLight = (SeekBar) contentView.findViewById(R.id.second_pop_seekbar);
        //检查系统亮度
        screenBrightnessCheck();

        seekBarLight.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                Log.d("NewsSecondActivity", "progress:" + progress);

                setScreenBritness(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //显示PopupWindow
        View rootview = LayoutInflater.from(NewsSecondActivity.this).inflate(R.layout.news_second_pop_window, null);
        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
        contentView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mPopWindow.dismiss();
                return false;
            }
        });

    }


    // onCreate()里检查系统亮度并设置seekBar
    private void screenBrightnessCheck() {
        //先关闭系统的亮度自动调节
        try {
            if (android.provider.Settings.System.getInt(getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE) == android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
                android.provider.Settings.System.putInt(getContentResolver(),
                        android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE,
                        android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            }
        } catch (Settings.SettingNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //获取当前亮度,获取失败则返回255
        int intScreenBrightness = (Settings.System.getInt(getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS,
                255));
        Log.d("屏幕亮度", "intScreenBrightness:" + intScreenBrightness);
        seekBarLight.setProgress(intScreenBrightness);
    }

    //屏幕亮度
    private void setScreenBritness(int brightness) {
        //不让屏幕全暗
        if (brightness <= 1) {
            brightness = 1;
        }
        //设置当前activity的屏幕亮度
        WindowManager.LayoutParams lp = this.getWindow().getAttributes();
        //0到1,调整亮度暗到全亮
        lp.screenBrightness = Float.valueOf(brightness / 255f);
        this.getWindow().setAttributes(lp);

        //保存为系统亮度方法1
//        android.provider.Settings.System.putInt(getContentResolver(),
//                android.provider.Settings.System.SCREEN_BRIGHTNESS,
//                brightness);

        //保存为系统亮度方法2
        Uri uri = android.provider.Settings.System.getUriFor("screen_brightness");
        android.provider.Settings.System.putInt(getContentResolver(), "screen_brightness", brightness);
//         resolver.registerContentObserver(uri, true, myContentObserver);
        getContentResolver().notifyChange(uri, null);

    }

    @Override
    protected void onStart() {
        super.onStart();
        try{
            MyBmobUser user = MyBmobUser.getCurrentUser(MyBmobUser.class);
            final String userName = user.getUsername();//当前登录的用户名
            if (user != null) {
                DBTool.getInstance().unRepetition("contentUrl = ?", url, "name = ?", userName, new DBTool.QueryListener() {
                    @Override
                    public void onQueryComplete(ArrayList<LocalBean> localBeenn) {
                        if (localBeenn.size() != 0) {
                            collectIv.setImageResource(R.mipmap.news_toolbar_icon_favorite_blue);
                        }else {
                        }
                    }
                });
            }
        }catch (Exception e){

        }

    }
}